#!/usr/bin/env perl

# Generate (pagrid) partitions with random G and R values
# And print the result in a way suitable for Gnuplot

# Basile Clout, December 2007

use Getopt::Long;

use strict;
use warnings;


sub usage(){
  print <<EOF;

Usage: ./autoBench.pl [-n number of partitions] [-d destination folder
(DEFAULT= AUTO)] [-l list file name] [-f random G and R values file]
<.node> <.ele> <.vmap>.

EOF
exit;
}

my $runBench_bin = "/root/export_cluster/code/tools/runBenchs.pl";
my $statPart_bin = "/root/export_cluster/code/tools/cutedges/statPart.pl";
my $minG;
my $maxG;
my $minR;
my $maxR;

my $n = 9;
my $dir="./auto";
my $flist="";
my $help;

my $logfile = "autoBench.log";
my $fgraph="testix.1.ngraph";
my $frandom="";

GetOptions("n=i"=>\$n, "d=s"=>\$dir, "l=s"=>\$flist, "f=s"=>\$frandom, "h"=>\$help);

usage() if ($help);
die "No random file $frandom" if (! -r $frandom);

die "Usage: autoBench.pl -n number <.node> <.ele> <.vmap>" if ($#ARGV != 2);
my ($f1, $f2, $f3) = ($ARGV[0], $ARGV[1], $ARGV[2]); 
unlink $flist if (-r $flist);

my $list="${dir}/$f1.pagrid.list.txt";
my @aG=();
my @aR=();

open LOG, ">$logfile" or die "Impossible to open log file $logfile: $!";


# Parse random file
my $fr=open(RANDOM, "<$frandom") or die "Impossible to open $frandom: $!";
my @content=<RANDOM>;

for my $line (@content){
  if ($line =~ /^#/){
    my @options = split /\s+/, $line;
    $n = $options[1];
    $minG = $options[2];
    $maxG = $options[3];
    $minR= $options[4];
    $maxR = $options[5];
  }else{
    my @nb = split /\s+/, $line;
    push @aG, $nb[0];
    push @aR, $nb[1];
  }
}

for my $i (0..$n-1){
  my $r=$aR[$i];
  my $g=$aG[$i];
  my $order = "$runBench_bin -i triangle -p pagrid -n 1 -m 0 -u basil -G $g -r $r --fast -d $dir -gr 0 $f1 $f2 $f3";
  print LOG "Order = $order";
open RUNBENCH, "$order |" or die "Impossible to run runBench.pl: $!";
my @runContent = <RUNBENCH>;
print LOG @runContent;

  open(AUTO, ">>$flist") or die "Impossible to open list file $flist: $!";
  open LIST, "<$list" or die "Impossible to open generation list $list: $!";
  my @content=<LIST>;
  chomp @content;
  rename $content[0], "$content[0]_${g}_${r}";
  print AUTO "@{content}_${g}_${r}\t\t$g\t$r\n";
  close(AUTO);
  close(LIST);
}

my $statOrder = "$statPart_bin --eet --ce -s -f $flist $fgraph $f3";
system($statOrder);

  






